package Thread.PC;

import com.sun.jndi.toolkit.ctx.AtomicContext;

import javax.xml.bind.SchemaOutputResolver;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}11:09
 */
class MyResource{
    private static AtomicInteger num = new AtomicInteger(0);
    //锁
    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    static void producer() throws InterruptedException {
        lock.lock();
        //进行条件判断
        try {
            while (num.get() != 0){
                condition.await();
            }
            num.getAndIncrement();
            System.out.println(Thread.currentThread().getName()+"生成"+num.get());
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    static void consume(){
        lock.lock();
        try {
            while (num.get() == 0){
                condition.await();
            }
            num.decrementAndGet();
            System.out.println(Thread.currentThread().getName()+"消费后"+num.get());
            condition.signalAll();
        }catch (InterruptedException E){
            System.out.println(E.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
public class ProdConsumerBolck {
    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 5; i++){
                try {
                    MyResource.producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() ->{
            for (int i = 0; i < 5; i++){
                MyResource.consume();
            }
        },"B").start();

    }
}
